package com.symaster.backups.frame.element.scrollbar;

import com.symaster.common.swing.util.SwingUtil;

import javax.swing.*;
import java.awt.*;
import java.util.Arrays;

/**
 * @author yinmiao
 * @version 2023/12/5
 */
public class ScrollbarTest {

    public static void main(String[] args) {
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new TileLayout());
        for (int i = 0; i < 100; i++) {
            jPanel.add(new JLabel("Hello" + i));
        }

        Scrollbar scrollbar = new Scrollbar();
        scrollbar.setContentPane(jPanel);

        Canvas canvas = new Canvas();
        canvas.add(scrollbar);

        JFrame jFrame = new JFrame("ScrollbarTest");
        jFrame.setContentPane(canvas);
        jFrame.setPreferredSize(new Dimension(600, 900));
        jFrame.pack();
        jFrame.setVisible(true);
        SwingUtil.toCenter(jFrame);
    }

    private static class Canvas extends JComponent {
        // private final FpsManager fpsManager = new FpsManager();

        @Override
        public void paint(Graphics g) {
            for (Component component : getComponents()) {
                component.setBounds(0, 0, getWidth(), getHeight());
            }

            super.paint(g);
            // fpsManager.paintRunnable(60, this::repaint);
        }
    }

    public static class TileLayout implements LayoutManager {

        @Override
        public void addLayoutComponent(String name, Component comp) {

        }

        @Override
        public void removeLayoutComponent(Component comp) {

        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {
            Component[] components = parent.getComponents();
            if (components == null) {
                return new Dimension(0,0);
            }
            Container parent1 = parent.getParent();
            Dimension size = parent1.getSize();

            return new Dimension(size.width, Arrays.stream(components).mapToInt(e -> e.getPreferredSize().height).sum());
        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {
            return preferredLayoutSize(parent);
        }

        @Override
        public void layoutContainer(Container parent) {
            Container parent1 = parent.getParent();
            Dimension size = parent1.getSize();

            int yOffset = 0;
            for (Component component : parent.getComponents()) {
                Dimension preferredSize = component.getPreferredSize();
                component.setBounds(0, yOffset, size.width, preferredSize.height);
                yOffset += preferredSize.height;
            }
        }
    }
}
